package org.paper.apolloSync;


import com.ctrip.framework.apollo.openapi.client.ApolloOpenApiClient;
import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO;
import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class ApolloConfigNameSpaceFilter  {
    public static List<String> syncedConfig=new ArrayList<>();
    public static void  saveToFile(List<NameSpaceData> nameSpaceDates) throws IOException {

        // 获取NameSpace 名称和配置项
        for (NameSpaceData nameSpaceData : nameSpaceDates){
            Properties properties = new Properties();
            for (OpenItemDTO items: nameSpaceData.items){
                properties.setProperty(items.getKey(), items.getValue());
            }
        //             将配置项写入文件
            try (OutputStreamWriter fileWriter = new OutputStreamWriter(Files.newOutputStream(nameSpaceData.fileName.toPath()), StandardCharsets.UTF_8)) {
                if (nameSpaceData.fileName.getName().endsWith(".properties")) {
                    properties.store(fileWriter, "Apollo Namespace: " + nameSpaceData.fileName.getName());
                } else if (nameSpaceData.fileName.getName().endsWith(".yml")) {
                    fileWriter.write(properties.getProperty("content"));
                } else {
                    throw new IllegalArgumentException("Unsupported format: " + nameSpaceData.fileName.getName());
                }
            }
            syncedConfig.add(nameSpaceData.fileName.getName());
            System.out.println("NameSpace "+nameSpaceData.fileName.getName()+"已从Apollo加载！"+"存放于"+nameSpaceData.fileName.getAbsolutePath());

        }
        System.setProperty("syncedConfig",syncedConfig.toString());

    }



    public static ApolloOpenApiClient apolloOpenApiClient() {
        String portalUrl=System.getProperty("apollo.portalUrl");
        String token=System.getProperty("apollo.token");

        return ApolloOpenApiClient.newBuilder()
                .withPortalUrl(portalUrl)
                .withToken(token)
                .build();
    }



    public static List<NameSpaceData> generateFileName(boolean nameInApollo) {
        String appid=System.getProperty("app.id");
        String env=System.getProperty("env","DEV");
        String clusterName=System.getProperty("apollo.cluster", "default");

        String serverRootDir=System.getProperty("server.root", "./");
        ApolloOpenApiClient client= apolloOpenApiClient();
        List<NameSpaceData> fileList = new ArrayList<>();

        List<OpenNamespaceDTO> namespaces=client.getNamespaces(appid,env,clusterName);
        // 构建文件路径和名称
        File outputDir = new File(serverRootDir); // 指定输出目录
        for (OpenNamespaceDTO namespace : namespaces){

            if (namespace.getNamespaceName().contains(".") || nameInApollo){
                fileList.add(new NameSpaceData(new File(outputDir, namespace.getNamespaceName()),namespace.getItems()));
            }
            else {

                fileList.add(new NameSpaceData(new File(outputDir,namespace.getNamespaceName()+"."+namespace.getFormat()),namespace.getItems()));
            }
        }

        return fileList;
    }
}
